{% set story_tags_list = story.tags.values() if story.tags is mapping else (story.tags or []) %}
{% set story_attributes = story.attributes or [] %}
{% set news_count = story.news_items | length %}
{% set read_badge = 'badge badge-success badge-sm' if story.read else 'badge badge-primary badge-sm' %}
{% set important_badge = 'badge badge-warning badge-sm' if story.important else none %}
{% set advanced_story_options = current_user.profile.advanced_story_options %}
{% set layout = layout | default('simple') %}
{% set column_class = 'col-span-4' if layout == 'advanced' else 'col-span-5' %}
{% set card_id = 'story-' ~ story_id %}
{% set toggled_read = (not (story.read | default(false))) | tojson %}
{% set toggled_important = (not (story.important | default(false))) | tojson %}
{% from "assess/news_item_card.html" import news_item_card %}

<section id="{{ card_id }}"
         class="space-y-6 p-6"
         hx-get="{{ url_for('assess.story_edit', story_id=story.id) }}"
         hx-trigger="story:reload from:body"
         hx-target="#{{ card_id }}"
         hx-swap="outerHTML"
         @keydown.shift.window="showHints = true"
         @keyup.shift.window="showHints = false"
         x-data="{ showHints: false }">

  {% if has_rt_id -%}
    <div class="alert alert-warning shadow-lg border border-warning/40">
      <span class="font-semibold text-sm">RT managed story detected.</span>
      <span class="text-sm">Please make any edits directly in RT to avoid conflicts; this interface is read-only for the record.</span>
    </div>
  {% endif -%}

  <!-- Story header -->
  <article class="card shadow-xl border border-base-200 bg-base-100">
    <div class="card-body grid gap-4 grid-cols-2">
      <div class="space-y-3">
        <p class="text-xs uppercase tracking-wide text-base-content/60">Story reference · {{ story.id }}</p>
        <h1 class="text-3xl font-semibold leading-tight tracking-tight">{{ story.title or "Untitled story" }}</h1>
        <div class="flex flex-wrap gap-2 text-xs">
          <span class="{{ read_badge }}">{{ 'Read' if story.read else 'Unread' }}</span>
          {% if important_badge %}<span class="{{ important_badge }}">Important</span>{% endif %}
          {% if story.relevance is not none %}<span class="badge badge-outline badge-sm">Relevance {{ story.relevance }}</span>{% endif %}
          {% if story.in_reports_count %}
            {% set report_count = story.in_reports_count | int %}
            <div class="tooltip gap-1 text-warning" data-tip="Story in {{ report_count }} Reports">
              {{ heroicon_mini("arrow-up-on-square", class="h-4 w-4") }}
            </div>
          {% endif %}
        </div>
      </div>
      <div class="flex flex-col gap-3">
        <div class="flex justify-end gap-2">
          <button type="button"
                  class="btn btn-outline btn-sm"
                  hx-trigger="click, keyup[shiftKey && code == 'R'] from:body"
                  hx-get="{{ url_for('assess.report_story') }}"
                  hx-target="body"
                  hx-swap="beforeend"
                  hx-vals='{"story_ids": "{{ story.id }}" }'
                  data-testid="share-story-to-report">
            {{ heroicon_mini("document-chart-bar") }}
            <span class="text-sm">Add to Report</span>
            <span class="text-xs opacity-80" x-show="showHints">
              <kbd class="kbd kbd-xs">Shift+R</kbd>
            </span>
          </button>
          <button type="button"
                  class="btn btn-outline btn-sm"
                  hx-trigger="click, keyup[shiftKey && code == 'E'] from:body"
                  hx-put="{{ url_for('assess.story', story_id=story_id) }}"
                  hx-vals='{"read": {{ toggled_read }} }'
                  hx-target="#{{ card_id }}"
                  hx-push-url="false"
                  hx-swap="outerHTML"
                  data-testid="toggle-read">
            {% if story.read | default(false) %}
              {{ heroicon_mini("eye-slash") }}
              <span>Mark unread</span>
            {% else %}
              {{ heroicon_mini("eye") }}
              <span>Mark read</span>
            {% endif %}
            <span class="text-xs opacity-80" x-show="showHints">
              <kbd class="kbd kbd-xs">Shift+E</kbd>
            </span>
          </button>
          <button type="button"
                  class="btn btn-outline btn-sm"
                  hx-trigger="click, keyup[shiftKey && code == 'I'] from:body"
                  hx-put="{{ url_for('assess.story', story_id=story_id) }}"
                  hx-vals='{"important": {{ toggled_important }} }'
                  hx-target="#{{ card_id }}"
                  hx-push-url="false"
                  hx-swap="outerHTML"
                  data-testid="toggle-important">
            {{ heroicon_mini("star") }}
            <span>
              {% if story.important | default(false) %}
                Remove important
              {% else %}
                Mark important
              {% endif %}
            </span>
            <span class="text-xs opacity-80" x-show="showHints">
              <kbd class="kbd kbd-xs">Shift+I</kbd>
            </span>
          </button>
          <div class="join">
            <a href="?layout=advanced" class="btn btn-sm join-item btn-outline {% if layout == 'advanced' %}btn-info btn-active{% endif %}">Advanced view</a>
            <a href="?layout=simple" class="btn btn-sm join-item btn-outline {% if layout == 'simple' %}btn-info btn-active{% endif %}">Simple view</a>
          </div>
        </div>
        <div class="grid gap-3 grid-cols-3">
          <div class="rounded-2xl border border-base-200 bg-base-200/40 px-4 py-3">
            <p class="text-xs font-semibold uppercase tracking-wide text-base-content/60">Created</p>
            <p class="text-sm font-medium">{{ story.created | format_datetime if story.created else "—" }}</p>
          </div>
          <div class="rounded-2xl border border-base-200 bg-base-200/40 px-4 py-3">
            <p class="text-xs font-semibold uppercase tracking-wide text-base-content/60">Updated</p>
            <p class="text-sm font-medium">{{ story.updated | format_datetime if story.updated else "—" }}</p>
          </div>
          <div class="rounded-2xl border border-base-200 bg-base-200/40 px-4 py-3">
            <p class="text-xs font-semibold uppercase tracking-wide text-base-content/60">News items</p>
            <p class="text-sm font-medium">{{ news_count }}</p>
          </div>
        </div>
      </div>
    </div>
  </article>

  <!-- Main content grid -->
  <div class="grid gap-4 grid-cols-5">
    <div class="space-y-6 {{ column_class }}">
      <form id="story-edit-form"
            class="card bg-base-100 shadow-xl border border-base-200"
            {{ form_action }}
            hx-target="#{{ card_id }}"
            hx-swap="outerHTML"
            hx-target-error="#notification-bar">
        <div class="card-body space-y-1">
          <header class="flex items-center justify-between">
            <h2 class="card-title text-xl">Editor</h2>
            <span class="badge badge-outline badge-sm">Autosave via submit</span>
          </header>
          <label class="input w-full">
            <span class="label justify-between">
              <span class="label-text font-semibold">Title<span aria-hidden="true" class="text-error">*</span></span>
            </span>
            <input type="text"
                   name="title"
                   value="{{ story.title }}"
                   required
                   class="input input-bordered input-primary input-lg"
                   placeholder="Enter story title">
          </label>

          <div class="grid grid-cols-2 gap-8">
            <label class="floating-label">
              <span class="label">Summary</span>
              <textarea name="summary" class="textarea textarea-bordered w-full" placeholder="Summarise the key takeaways">{{ story.summary }}</textarea>
            </label>

            <label class="floating-label">
              <span class="label">Analyst comments</span>
              <textarea name="comments" class="textarea textarea-bordered w-full" placeholder="Capture notes, caveats, or next steps">{{ story.comments }}</textarea>
            </label>
            {# djlint:off #}
            <section class="rounded-2xl border border-base-200 bg-base-200/40 p-5 h-full"
                     x-data='{ tags: {{ story_tags_list | list | tojson }}, init() { if (!Array.isArray(this.tags)) { this.tags = Object.values(this.tags || {}); } if (this.tags.length === 0) { this.tags.push({ "name": "", "tag_type": "" }); } }, addTag() { this.tags.push({ "name": "", "tag_type": "" }); }, removeTag(index) { this.tags.splice(index, 1); if (this.tags.length === 0) { this.tags.push({ "name": "", "tag_type": "" }); } } }'>
              <div class="flex items-center justify-between gap-4">
                <h3 class="text-lg font-semibold">Tags</h3>
                <button type="button" class="btn btn-outline btn-sm" @click="addTag()">Add tag</button>
              </div>
              <p class="text-xs text-base-content/60 mt-1">Tags are saved with their type; leave a field blank to remove it on save.</p>
              <div class="mt-4 flex flex-col gap-3">
                <template x-for="(tag, index) in tags" :key="index">
                  <div class="flex gap-3">
                    <input class="input input-bordered input-sm flex-grow" type="text" x-model="tag.name" name="tags[][name]" data-testid="tag-name-input" placeholder="Tag name">
                    <input class="input input-bordered input-sm flex-grow" type="text" x-model="tag.tag_type" name="tags[][tag_type]" data-testid="tag-value-input" placeholder="Tag type (e.g. misc, location, actor)">
                    <button type="button" class="btn btn-ghost btn-xs text-error flex-shrink" @click="removeTag(index)">Remove</button>
                  </div>
                </template>
              </div>
            </section>

            <section class="rounded-2xl border border-base-200 bg-base-200/40 p-5 h-full"
                     x-data='{ attributes: {{ story_attributes | tojson }}, init() { if (!Array.isArray(this.attributes)) { this.attributes = Object.values(this.attributes || {}); } if (this.attributes.length === 0) { this.attributes.push({ "key": "", "value": "" }); } }, addAttribute() { this.attributes.push({ "key": "", "value": "" }); }, removeAttribute(index) { this.attributes.splice(index, 1); if (this.attributes.length === 0) { this.attributes.push({ "key": "", "value": "" }); } } }'>
              <div class="flex items-center justify-between gap-4">
                <h3 class="text-lg font-semibold">Attributes</h3>
                <button type="button" class="btn btn-outline btn-sm" @click="addAttribute()">Add attribute</button>
              </div>
              <p class="text-xs text-base-content/60 mt-1">Attributes are stored as key/value pairs. Unsupported keys are preserved as-is.</p>
              <div class="mt-4 flex flex-col gap-3">
                <template x-for="(attribute, index) in attributes" :key="index">
                  <div class="flex gap-3">
                    <input class="input input-bordered input-sm flex-grow" type="text" x-model="attribute.key" name="attributes[][key]" data-testid="attribute-key-input" placeholder="Key (e.g. TLP)">
                    <input class="input input-bordered input-sm flex-grow" type="text" x-model="attribute.value" name="attributes[][value]" data-testid="attribute-value-input" placeholder="Value">
                    <button type="button" class="btn btn-ghost btn-xs text-error flex-shrink" @click="removeAttribute(index)">Remove</button>
                  </div>
                </template>
              </div>
            </section>
            {# djlint:on #}
          </div>

          <footer class="flex flex-col gap-3 sm:flex-row sm:items-center">
            <button type="submit" class="btn btn-primary sm:w-48" {% if has_rt_id %}disabled{% endif %}>Save changes</button>
            <a href="{{ url_for('assess.story', story_id=story.id) }}" class="btn btn-ghost sm:w-48">Return to story</a>
            {% if has_rt_id %}<p class="text-xs text-error sm:ml-4">Editing disabled for RT managed stories.</p>{% endif %}
          </footer>
        </div>
      </form>
    </div>

    {% if layout == 'advanced' %}
      <!-- Advanced options sidebar -->
      <aside class="space-y-2">
        <div class="card bg-base-100 shadow-lg border border-base-200">
          <div class="card-body space-y-4">
            <h3 class="card-title text-lg">Story status</h3>
            <div class="flex flex-wrap gap-3 text-sm">
              <span class="{{ cyber_chip_class }}">Cybersecurity · {{ story_cyber_status }}</span>
            </div>
          </div>
        </div>

        <div class="card bg-base-100 shadow-lg border border-base-200">
          <div class="card-body space-y-3">
            <h3 class="card-title text-lg">AI assisted actions</h3>
            <p class="text-sm text-base-content/70">
              Kick off automation and keep the panel open while tasks run. Results will refresh automatically when finished.
            </p>

            <form class="flex flex-col"
                  hx-post="{{ url_for('assess.story_trigger_bot', story_id=story.id) }}"
                  hx-target="#notification-bar"
                  hx-swap="innerHTML">
              <input type="hidden" name="bot_id" value="summary_bot">
              <button type="submit" class="btn btn-outline btn-accent" {% if has_rt_id %}disabled{% endif %}>Generate AI summary</button>
            </form>

            <form class="flex flex-col"
                  hx-post="{{ url_for('assess.story_trigger_bot', story_id=story.id) }}"
                  hx-target="#notification-bar"
                  hx-swap="innerHTML">
              <input type="hidden" name="bot_id" value="sentiment_analysis_bot">
              <button type="submit" class="btn btn-outline btn-accent" {% if has_rt_id %}disabled{% endif %}>Run sentiment analysis</button>
            </form>

            <form class="flex flex-col"
                  hx-post="{{ url_for('assess.story_trigger_bot', story_id=story.id) }}"
                  hx-target="#notification-bar"
                  hx-swap="innerHTML">
              <input type="hidden" name="bot_id" value="cybersec_classifier_bot">
              <button type="submit" class="btn btn-outline btn-accent" {% if has_rt_id %}disabled{% endif %}>Cybersecurity classification</button>
            </form>
          </div>
        </div>
      </aside>
    {% endif %}
  </div>

  <div class="card bg-base-100 shadow-lg border border-base-200">
    <div class="card-body space-y-5">
      <div class="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
        <h3 class="card-title text-lg">Linked news items ({{ news_count }})</h3>
      </div>

      {% if story.news_items %}
        <div class="space-y-4">
          {% for item in story.news_items %}{{ news_item_card(item) }}{% endfor %}
        </div>
      {% else %}
        <p class="text-sm text-base-content/70">No news items are attached to this story yet.</p>
      {% endif %}
    </div>
  </div>
</section>
